// go:build v1
package v1

import (
	"net/http"
)

type HandleFunc func(ctx *Context)

type Server interface {

	// Handler 回调函数
	http.Handler

	// Start 开启服务 监听端口
	Start(addr string) error

	// AddRoute 注册路由
	AddRoute(method string, path string, handler HandleFunc)
}

// HttpServer web服务
type HttpServer struct {
	router
}

var (
	// 匿名变量 确保 HTTPServer 肯定实现了 Server 接口
	_ Server = &HttpServer{}
)

func NewHttpServer() *HttpServer {
	return &HttpServer{
		router: newRouter(),
	}
}

func (s *HttpServer) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	ctx := &Context{
		Req:  request,
		Resp: writer,
	}
	s.serve(ctx)
}

func (s *HttpServer) Start(addr string) error {
	return http.ListenAndServe(addr, s)
}

func (s *HttpServer) AddRoute(method string, path string, handler HandleFunc) {
	s.addRoute(method, path, handler)
}

func (s *HttpServer) serve(ctx *Context) {
	mi, ok := s.findRoute(ctx.Req.Method, ctx.Req.URL.Path)
	if !ok || mi == nil || mi.n.handler == nil {
		ctx.Resp.WriteHeader(http.StatusNotFound)
		ctx.Resp.Write([]byte("Not Found"))
		return
	}
	ctx.PathParams = mi.pathParams
	mi.n.handler(ctx)
}

func (s *HttpServer) Get(path string, handler HandleFunc) {
	s.addRoute(http.MethodGet, path, handler)
}

func (s *HttpServer) Post(path string, handler HandleFunc) {
	s.addRoute(http.MethodPost, path, handler)
}
